package cn.wolfcode.luowowo.webSite.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.WendaAnswerQuery;
import cn.wolfcode.luowowo.article.query.WendaQuestionQuery;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.cache.domain.WendaStatisVO;
import cn.wolfcode.luowowo.cache.service.IWendaStatisRedisService;
import cn.wolfcode.luowowo.common.domain.WendaAnswerComment;
import cn.wolfcode.luowowo.common.query.WendaAnswerCommentQuery;
import cn.wolfcode.luowowo.common.service.IWendaAnswerCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.webSite.annotation.RequireLogin;
import cn.wolfcode.luowowo.webSite.annotation.UserParam;
import cn.wolfcode.luowowo.webSite.util.UMEditorUploader;
import cn.wolfcode.luowowo.webSite.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("wenda")
public class WendaController {

    @Reference
    private IWendaQuestionService wendaQuestionService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IRegionService regionService;
    @Reference
    private IWendaTagService wendaTagService;
    @Reference
    private IWendaQuestionContentService questionContentService;
    @Reference
    private IWendaAnswerService wendaAnswerService;
    @Reference
    private IWendaAnswerCommentService wendaAnswerCommentService;
    @Reference
    private IWendaStatisRedisService wendaStatisRedisService;


    @RequestMapping("")
    public String wenda(Model model){
        List<WendaStatisVO> comments = wendaStatisRedisService.getAllWendaStatisVOs();
        //获取排名前5的
        model.addAttribute("comments",comments);
        return "/wenda/wenda";
    }

    @RequestMapping("questionList")
    public String getQuestionList(Model model,@ModelAttribute("qo") WendaQuestionQuery qo){
        qo.setState(WendaQuestion.STATE_RELEASE);
        PageInfo<WendaQuestion> page = wendaQuestionService.query(qo);
        //查询评论明细数据
        List<WendaQuestion> list = page.getList();
        for (int i=0;i<list.size();i++) {
            WendaQuestion wendaQuestion = list.get(i);
            wendaQuestion.setWendaQuestionContent(wendaQuestionService.getContent(wendaQuestion.getId()));
            WendaStatisVO vo = wendaStatisRedisService.getWendaStatisVO(wendaQuestion.getId());
            if (vo!=null){
                wendaQuestion.setViewNum(vo.getViewnum());
                wendaQuestion.setReplyNum(vo.getReplynum());
            }
        }
        model.addAttribute("pageInfo",page);
        return "wenda/questionList";
    }


    //查询目的地
    @RequestMapping("getRegion")
    @ResponseBody
    @RequireLogin
    public Object getRegion(){
        //返回目的地的相关数据
        List<Destination> hotDests = destinationService.queryHotDest();      //热门目的地
        List<Destination> islandDests = destinationService.queryProvince();  //国内目的地
        List<Region> regions = regionService.queryRegions();                //地区

        for (Region region : regions) {
            List<Destination> destByRegionId = destinationService.getDestByRegionId(region.getId());
            region.setChildren(destByRegionId);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("hotDests",hotDests);
        map.put("islandDests",islandDests);
        map.put("regions",regions);
        return map;
    }

    //查询标签
    @RequestMapping("input")
    @RequireLogin
    public String getTags(Model model){
        List<WendaTag> tags = wendaTagService.selectAll();
        model.addAttribute("tags",tags);
        return "wenda/publish";
    }

    /**
     * 我要提问
     * @return
     */
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequireLogin
    public Object saveOrUpdate(WendaQuestion wendaQuestion, Long tagId, @UserParam UserInfo userInfo){
        wendaQuestion.setAuthor(userInfo);
        Long wendaId = wendaQuestionService.saveOrUpdate(wendaQuestion,tagId);
        return new AjaxResult().addData(wendaId);
    }

    @RequestMapping("/wendaDetail")
    @RequireLogin
    public String wendaDetail(Model model,Long id,@UserParam UserInfo userInfo){
        //查出问题id对应的问题内容,回显
        WendaQuestion question = wendaQuestionService.selectByPrimaryKey(id);
        WendaQuestionContent content = wendaQuestionService.getContent(id);
        question.setWendaQuestionContent(content);
        question.setAuthor(userInfo);
        //查出id对应的标签,回显
        //自定义方法查出所有标签集合
        List<WendaTag> tags = wendaTagService.getTags(id);
        model.addAttribute("tags",tags);
        // 每访问一次页面，浏览量+1, 回显数据
        wendaStatisRedisService.viewnumIncrease(id,1);
        WendaStatisVO vo = wendaStatisRedisService.getWendaStatisVO(id);
        try {
            BeanUtils.copyProperties(question,vo);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        model.addAttribute("question",question);
        model.addAttribute("vo",vo);
        //判断用户是否登陆,登陆就回显
        if (userInfo != null){
            model.addAttribute("userInfo",userInfo);
        }
        model.addAttribute("questionId",id);
        return "wenda/wendaDetail";
    }

    @RequestMapping("/saveAnswer")
    @ResponseBody
    public Object saveAnswer(@UserParam UserInfo userInfo,WendaAnswerComment wendaAnswerComment){
        if (userInfo == null){
            return new AjaxResult(false,"请先登陆");
        }
        wendaAnswerComment.setUserId(userInfo.getId());
        wendaAnswerComment.setUsername(userInfo.getNickname());
        wendaAnswerComment.setLevel(userInfo.getLevel());
        wendaAnswerComment.setHeadUrl(userInfo.getHeadImgUrl());
        wendaAnswerCommentService.saveOrUpdate(wendaAnswerComment);
        return new AjaxResult().addData(wendaAnswerComment.getQuestionId());
    }

    @RequestMapping("/answerList")
    @RequireLogin
    public String  answerList(Model model,@ModelAttribute("qo") WendaAnswerCommentQuery qo){
        Page page = wendaAnswerCommentService.query(qo);
        model.addAttribute("page",page );
        return "wenda/wendaAnswerList";
    }


    @RequestMapping("/wendaThumbsup")
    @ResponseBody
    public Object wendaThumbsup(String aid,@UserParam UserInfo userInfo,Long uid){
        //登陆判断
        if(userInfo==null){
            AjaxResult result = new AjaxResult(false,"请先登录");
            result.setCode(102);//未登录时的状态码
            return result;
        }
//        boolean ret = wendaStatisRedisService.thumbsupnumIncrease(tid,userInfo.getId());

        boolean ret = wendaAnswerCommentService.thumbsupnumIncrease(aid,uid);

        //WendaAnswerComment comment = wendaAnswerCommentService.get(aid);
        return new AjaxResult(ret).addData(wendaAnswerCommentService.getByid(aid));
    }


    /*@RequestMapping("/search")
    @ResponseBody
    public Object search(Model model,@ModelAttribute WendaQuestionQuery qo){
        PageInfo query = wendaQuestionService.queryConcat(qo);
        model.addAttribute("query",query);
        return new AjaxResult().addData(query);
    }*/



    //富文本框保存图片
    @Value("${file.path}")
    private String filePath;

    //封面处理
    @RequestMapping("/coverImageUpload")
    @ResponseBody  //插件要求必须返回Json
    public Object coverImageUpload(MultipartFile pic) {
        String filename = UploadUtil.upload(pic, filePath);
        return filename;
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

}
